package com.wzz.auth.cust;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wzz.auth.cache.Cache;
import com.wzz.auth.cust.moudle.SendRedirect;
import com.wzz.auth.po.GetCodeParam;
import com.wzz.auth.po.GetTokenParam;
import com.wzz.auth.po.ReceCode;

@Controller
public class CustControllerNew {
	
	@Autowired
	Cache cache ;
	
	@RequestMapping("cust/start")
	public void start(String name , HttpServletRequest request, HttpServletResponse response) {
		SendRedirect sr = new SendRedirect(response);
		
		GetCodeParam param = new GetCodeParam();
		try {
			
			String state = System.currentTimeMillis()+"";
			
			cache.getMap().put(state, name);
			cache.getMap().put(state+"url", "http://localhost:8080/AuthCust/cust/start?state="+state);
			
			param.setResponse_type("code");
			param.setClient_id("123");
			param.setState(state);
			param.setRedirect_uri("http://localhost:8080/AuthCust/cust/rece");
			
			List<String> list = new ArrayList<String>();
			list.add("a");
			list.add("b");
			param.setScope(list);
			
			
			sr.sendRedirect("http://localhost:8080/AuthServer/server/a", param);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("cust/rece")
	public void rece(String token, ReceCode rc, HttpServletRequest request, HttpServletResponse response) {
		
		if(token ==null || "".equals(token)) {
			System.out.println("接收code....");
			
			cache.getMap().put(rc.getState()+"code", rc.getCode());
			
			System.out.println("code="+rc.getCode());
			
			GetTokenParam param = new GetTokenParam();
			param.setClient_id("123");
			param.setCode(rc.getCode());
			param.setGrant_type("authorization_code");
			param.setRedirect_uri("http://localhost:8080/AuthCust/cust/rece");
			
			SendRedirect sr = new SendRedirect(response);
			try {
				sr.sendRedirect("http://localhost:8080/AuthServer/get/token", param);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			System.out.println("接收token");
			System.out.println(token);
			
			try {
				response.getOutputStream().write(token.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
	
	public static void main(String[] args) {
		CustControllerNew c = new CustControllerNew();
		c.start("wzz", null, null);
	}
}
